package my;

import java.io.IOException;
import java.net.*;

abstract class UDPClient {
    private String ip;
    private int port;
    private InetAddress address;
    private DatagramSocket socket;
    private DatagramPacket datagramPacket;
    private DatagramPacket backPacket;
    private ReadThread mReadThread;

    private boolean _isConnected = false;

    public UDPClient(String ip, int port) {
        this.ip = ip;
        this.port = port;
    }

    public void connect() {
        try {
            address = InetAddress.getByName(this.ip);
            socket = new DatagramSocket();
            this.mReadThread = new UDPClient.ReadThread();
            this.mReadThread.start();
            this._isConnected = true;
        } catch (Exception ed) {
            MyFrame.appendText(ed.getMessage());
            ed.printStackTrace();
        }
    }

    public void close() {
        UDPClient.this.socket.close();
        this._isConnected = false;
    }

    public boolean isConnected() {
        return this._isConnected;
    }

    public void send(byte[] bOutArray) {
        datagramPacket = new DatagramPacket(bOutArray, bOutArray.length, this.address, this.port);
        try {
            this.socket.send(datagramPacket);
        } catch (IOException e) {
            MyFrame.appendText(e.getMessage());
            e.printStackTrace();
        }
    }

    protected abstract void onDataReceive(byte[] bytes, int size);

    private class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (!isInterrupted()) {
                try {
                    if (UDPClient.this.address == null) {
                        return;
                    }
                    byte[] backbuf = new byte[1024];
                    backPacket = new DatagramPacket(backbuf, backbuf.length);
                    UDPClient.this.socket.receive(backPacket);
                    String backMsg = new String(backbuf, 0, backPacket.getLength());
                    onDataReceive(backbuf, backPacket.getLength());
                    //MyFrame.appendText(backMsg);
                } catch (Throwable e) {
                    //System.out.println(e.getMessage());
                    MyFrame.appendText(e.getMessage());
                    return;
                }
            }
        }
    }


}
